﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 创建者：王明亮
 * 创建时间：2023/9/25 10:34:20
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using JwtApiDemo.Log4;
using JwtApiDemo.Models;
using System.Collections.Generic;
using System.Configuration;

namespace JwtApiDemo.Helper
{
    /// <summary>
    /// JWT获取和验证帮助类
    /// </summary>
    public class JwtHelper
    {
        /// <summary>
        /// 日志
        /// </summary>
       private static Logger  _logger = new Logger();

        /// <summary>
        /// 私钥appsettings.json中配置
        /// </summary>
        private static string secret =  ConfigHelper.GetSectionValue("TokenSecret");

        /// <summary>
        /// 生成JwtToken
        /// </summary>
        /// <param name="payload">不敏感的用户数据</param>
        /// <returns></returns>
        public static string SetJwtEncode(Dictionary<string, object> payload)
        {
            try
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

                var token = encoder.Encode(payload, secret);
                return token;
            }
            catch (System.Exception ex)
            {
                _logger.Error(ex.Message);
                return null;
            }

        }

        /// <summary>
        /// 根据jwtToken获取实体
        /// </summary>
        /// <param name="token">jwtToken</param>
        /// <returns></returns>
        public static LoginUserInfo GetJwtDecode(string token)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, urlEncoder);
                //IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                var userInfo = decoder.DecodeToObject<LoginUserInfo>(token, secret, verify: true);//token为之前生成的字符串
                return userInfo;
            }
            catch (System.Exception ex)
            {
                _logger.Error(ex.Message);
                return null;
            }

        }

    }
}
